package service;

import Bean.*;
import DAO.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author jianjun
 * @Describe
 * @creat 2022-01-01-21:35
 */
public class OrderServiceImpl implements OrderService {
    OrderDAO orderDAO = new OrderDAOImpl();
    OrderItemDAO orderItemDAO = new OrderItemDAOImpl();
    BookDAO bookDAO = new BookDAOImpl();

    @Override
    public String createOrder(Cart cart, Integer userId) {
        //订单号要有唯一性：时间戳+用户id
        String order_id = System.currentTimeMillis() + "" + userId;
        //保存订单
        Order order = new Order(order_id, new Date(), cart.getTotalPrice(), 0, userId);
        orderDAO.saveOrder(order);

        //遍历购物车中每一个商品项转换成为订单项保存到数据库
        for (Map.Entry<Integer, CartItem> entry : cart.getItems().entrySet()) {
            //保存订单项
            CartItem cartItem = entry.getValue();
            OrderItem orderItem = new OrderItem(cartItem.getName(), cartItem.getPrice(), cartItem.getTotalPrice(), cartItem.getCount(), order_id);
            orderItemDAO.saveOrderItem(orderItem);

            //修改库存和销量
            Book book = bookDAO.queryBookById(cartItem.getId());
            book.setSales(book.getSales() + cartItem.getCount());
            book.setStock(book.getStock() - cartItem.getCount());
            bookDAO.updateBook(book);
        }
        //通常点结账后，要清空购物车
        cart.clear();
        return order_id;
    }

    @Override
    public List<Order> showAllOrder() {
        return orderDAO.queryOrders();
    }


    @Override
    public void sendOrder(String order_id) {
        orderDAO.changeOrderStatus(order_id, 1);
    }

    @Override
    public List<OrderItem> showOrderDetail(String order_id) {
        return orderItemDAO.queryOrderItemsByOrderId(order_id);
    }

    @Override
    public List<Order> showMyOrders(Integer user_id) {
        return orderDAO.queryOrdersByUserId(user_id);
    }


    @Override
    public void receiveOrder(String order_id) {
        orderDAO.changeOrderStatus(order_id, 2);
    }
}
